package com.buyouchina.web.action.privilege;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import com.buyouchina.bean.area.Area;
import com.buyouchina.bean.area.Province;
import com.buyouchina.bean.privilege.Department;
import com.buyouchina.bean.privilege.PrivilegeGroup;
import com.buyouchina.bean.privilege.User;
import com.buyouchina.bean.product.Outlets;
import com.buyouchina.service.area.ProvinceService;
import com.buyouchina.service.privilege.DepartmentService;
import com.buyouchina.service.privilege.PrivilegeGroupService;
import com.buyouchina.service.privilege.UserService;
import com.buyouchina.service.product.OutletsService;
import com.buyouchina.utils.Pagination;
import com.buyouchina.utils.ProvinceUtil;
import com.buyouchina.utils.SiteUrl;
import com.buyouchina.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@Controller("UserManage")
public class UserManageAction extends BaseAction implements ModelDriven<User>,
		Preparable {
	private static final long serialVersionUID = 3616545118701361680L;
	@Resource(name = "userServiceBean")
	private UserService userService;
	@Resource
	private PrivilegeGroupService privilegeGroupService;
	@Resource(name = "provinceServiceBean")
	private ProvinceService provinceService;
	@Resource(name = "outletsServiceBean")
	private OutletsService outletsService;
	@Resource
	private DepartmentService departmentService;
	private Integer departmentid;
	private User user;
	private Integer userid;
	private Integer[] ids;
	private Integer[] groupids;
	private Area area;
	private Province province;
	private List<Department> departmentList = new ArrayList<Department>();
	private List<Province> provinceList = new ArrayList<Province>();
	private Set<Province> provinceSet = new HashSet<Province>();
	private List<User> userList = new ArrayList<User>();

	private String password; // 新密码
	private String oldPassword; // 旧密码
	private String passwordConfirm; // 确认密码
	private Integer provinceid; // 区域id
	private String queryString; // 查询字符串

	// 人员列表
	@Permission(model = "system", privilegeValue = "userManage")
	public String list() {

		Outlets ot = (Outlets) session.get("outlets");

		// 有店铺session 按店铺查找
		if (ot.getId() != 1) {
			userList = userService.list(ot.getId());
		} else { // 总部人员查询
			Pagination pg = new Pagination(request, response);
			user = (User) session.get("user");
			if (provinceid != null) {
				Long totalcount = userService.getCount();
				pg.setRecordCount(totalcount.intValue());
				userList = userService.list(pg.getFirstResult(), pg
						.getPageSize(), provinceid, ProvinceUtil
						.getLastIndexOfProvince(provinceService, provinceid));
			} else {
				Long totalcount = userService.getCount();
				pg.setRecordCount(totalcount.intValue());
				userList = userService.getScrollData(pg.getFirstResult(),
						pg.getPageSize()).getResultlist();
			}
			request.setAttribute("pagination", pg);
		}
		return "list";
	}

	// 店长列表
	public String managerList() {
		userList = userService.listManager(provinceid, ProvinceUtil
				.getLastIndexOfProvince(provinceService, provinceid));
		return "managerSelect";
	}

	// 人员查询
	public String userQuery() {
		Pagination pg = new Pagination(request, response);
		int totalcount = userService.list(queryString).size();
		pg.setRecordCount(totalcount);
		userList = userService.list(pg.getFirstResult(), pg.getPageSize(),
				queryString);
		return "list";
	}

	// 更新密码UI
	public String modifyPasswordUI() {
		return "modifyPassword";
	}

	// 更新密码
	public String modifyPassword() {
		if (!"".equals(oldPassword) && !"".equals(password)
				&& !"".equals(passwordConfirm)) {
			if (userService.checkUser(((User) session.get("user")).getPhone(),
					oldPassword)) {
				if (password.equals(passwordConfirm)) {
					userService.updatePassword(((User) session.get("user"))
							.getPhone(), password);
					request.setAttribute("message", "密码 修改成功");
					request.setAttribute("urladdress", SiteUrl
							.readUrl("control.right"));
					return "message";
				} else {
					this.addActionError("新密码要与确认密码一致");
					return "modifyPassword";
				}

			} else {
				this.addActionError("旧密码错误");
				return "modifyPassword";
			}

		} else {
			this.addActionError("旧密码,新密码,确认密码不能为空");
			return "modifyPassword";
		}
	}

	// 添加用户
	@Permission(model = "user", privilegeValue = "insert")
	public String addUser() {
		Outlets outlets = (Outlets) session.get("outlets");
		if (user.getPhone() != null && !user.getPhone().trim().equals("")
				&& !userService.exsit(user.getPhone().trim())) {
			province = provinceService.list(
					"select p from Province p where p.id='" + province.getId()
							+ "'").get(0);
			user.getProvinces().add(province);

			user.setDepartment((Department) departmentService
					.find(departmentid));

			user.setPassword(user.getPhone().substring(3));
			// user.setGroups(outlets.getManager().getGroups());
			userService.save(user);

			if (outlets.getId() != 1) {
				outlets.getUsers().add(user);
				outletsService.update(outlets);
			}
			request.setAttribute("message", "人员添加成功");
			request.setAttribute("urladdress", SiteUrl.readUrl("user.list"));
			return "message";
		} else {
			request.setAttribute("message", "用户名已经存在");
		}
		request.setAttribute("departments", departmentService.getScrollData()
				.getResultlist());
		return "add";
	}

	// 修改用户UI
	@Permission(model = "user", privilegeValue = "update")
	public String editUser() {
		departmentList = departmentService.getScrollData().getResultlist();
		String sql = "select p from Province p where p.cityid is null and p.provinceid is null";
		provinceList = provinceService.list(sql);
		return "edit";
	}

	// 更新用户
	public String updateUser() {
		if (departmentid != null) {
			user.setDepartment((Department) departmentService
					.find(departmentid));
		}
		if (province != null) {
			province = provinceService.list(
					"select p from Province p where p.id='" + province.getId()
							+ "'").get(0);
			user.getProvinces().clear();
			user.addProvince(province);
		}
		userService.update(user);
		request.setAttribute("message", "信息修改成功");
		request.setAttribute("urladdress", SiteUrl.readUrl("user.list"));
		return "message";
	}

	// 用户查询
	@Permission(model = "user", privilegeValue = "query")
	public String query() {
		return "query";
	}

	// 异步判断用户是否存在
	public String exist() {
		if (userService.exsit(user.getPhone().trim())) {
			request.setAttribute("message", "手机号码已经注册过!");
		} else {
			request.setAttribute("message", "手机号码不存在，可以注册");
		}
		return "usernameIsExsit";
	}

	// 启用
	@Permission(model = "user", privilegeValue = "enable")
	public String enable() {
		userService.setVisibleStatu(ids, true);
		request.setAttribute("message", "用户启用成功");
		request.setAttribute("urladdress", SiteUrl.readUrl("user.list"));
		return "message";
	}

	// 禁用
	@Permission(model = "user", privilegeValue = "disable")
	public String disable() {
		userService.setVisibleStatu(ids, false);
		request.setAttribute("message", "用户禁用成功");
		request.setAttribute("urladdress", SiteUrl.readUrl("user.list"));
		return "message";
	}

	// 用户权限设置UI
	@Permission(model = "user", privilegeValue = "privilegeGroupSet")
	public String privilegeGroupSetUI() {
		request.setAttribute("groups", privilegeGroupService.getScrollData()
				.getResultlist());
		request.setAttribute("usergroups", user.getGroups());
		return "privilegeGroupSet";
	}

	// 设置权限
	public String privilegeGroupSet() {
		user.getGroups().clear();
		for (Integer groupid : groupids) {
			user.addPrivilegeGroup(new PrivilegeGroup(groupid));
		}
		userService.update(user);
		request.setAttribute("message", "权限设置成功");
		request.setAttribute("urladdress", SiteUrl.readUrl("user.list"));
		return "message";
	}

	// MODEL DRIVEN
	public User getModel() {
		return user;
	}

	public void prepare() throws Exception {
		if (userid == null || "".equals(userid)) {
			user = new User();
		} else {
			user = userService.find(userid);
		}

	}

	// getter and setter
	public Area getArea() {
		return area;
	}

	public void setArea(Area area) {
		this.area = area;
	}

	public Province getProvince() {
		return province;
	}

	public void setProvince(Province province) {
		this.province = province;
	}

	public ProvinceService getProvinceService() {
		return provinceService;
	}

	public void setProvinceService(ProvinceService provinceService) {
		this.provinceService = provinceService;
	}

	public Integer getDepartmentid() {
		return departmentid;
	}

	public void setDepartmentid(Integer departmentid) {
		this.departmentid = departmentid;
	}

	public List<Department> getDepartmentList() {
		return departmentList;
	}

	public void setDepartmentList(List<Department> departmentList) {
		this.departmentList = departmentList;
	}

	public List<Province> getProvinceList() {
		return provinceList;
	}

	public void setProvinceList(List<Province> provinceList) {
		this.provinceList = provinceList;
	}

	public Set<Province> getProvinceSet() {
		return provinceSet;
	}

	public void setProvinceSet(Set<Province> provinceSet) {
		this.provinceSet = provinceSet;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getPasswordConfirm() {
		return passwordConfirm;
	}

	public void setPasswordConfirm(String passwordConfirm) {
		this.passwordConfirm = passwordConfirm;
	}

	public Integer[] getGroupids() {
		return groupids;
	}

	public void setGroupids(Integer[] groupids) {
		this.groupids = groupids;
	}

	public Integer getUserid() {
		return userid;
	}

	public void setUserid(Integer userid) {
		this.userid = userid;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public Integer getProvinceid() {
		return provinceid;
	}

	public void setProvinceid(Integer provinceid) {
		this.provinceid = provinceid;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}
}
